package cn.org.rookie.jeesdp.core.quartz;

import org.quartz.*;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.UUID;

/**
 * @author LHT
 * @date 2022-10-27 19:50
 */

public class QuartzUtils implements ApplicationContextAware, InitializingBean {

    private static Scheduler scheduler;
    private ApplicationContext applicationContext;

    public static void scheduleJob(String id, ScheduleBuilder<? extends Trigger> scheduleBuilder, Class<? extends Job> jobClass, JobDataMap data) {
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(id).setJobData(data).build();
        String triggerId = UUID.randomUUID().toString().replace("-", "");
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerId).withSchedule(scheduleBuilder).build();
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public static void scheduleJob(String id, int seconds, Class<? extends Job> jobClass, JobDataMap data) {
        scheduleJob(id, SimpleScheduleBuilder.repeatSecondlyForever(seconds), jobClass, data);
    }

    public static void scheduleJob(String id, int seconds, Class<? extends Job> jobClass) {
        scheduleJob(id, SimpleScheduleBuilder.repeatSecondlyForever(seconds), jobClass, null);
    }

    public static void scheduleJob(String id, String corn, Class<? extends Job> jobClass, JobDataMap data) {
        scheduleJob(id, CronScheduleBuilder.cronSchedule(corn), jobClass, data);
    }

    public static void scheduleJob(String id, String corn, Class<? extends Job> jobClass) {
        scheduleJob(id, corn, jobClass, null);
    }

    public static void deleteJob(String id) {
        try {
            scheduler.deleteJob(JobKey.jobKey(id));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public static void claer() {
        try {
            scheduler.clear();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public static boolean isValidExpression(String cron) {
        return CronExpression.isValidExpression(cron);
    }

    @Override
    public void afterPropertiesSet() {
        scheduler = applicationContext.getBean(Scheduler.class);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
